package com.lgCore.common;

import io.netty.channel.ChannelHandlerContext;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务端管理客户端的session，客户端连接管理
 */
@Slf4j
@Data
public class SessionManger {
    private static SessionManger singleInstance = null;
    /*本地会话集合*/
    private static ConcurrentHashMap<String, LocalSession> localSessionMap = new ConcurrentHashMap();


    public static SessionManger inst() {
        return singleInstance;
    }

    public static void setSingleInstance(SessionManger singleInstance) {
        SessionManger.singleInstance = singleInstance;
    }

    /**
     * 登录成功之后， 增加session对象
     */
    public static void addLocalSession(LocalSession session) {
        String clientId = session.getClientId();
        localSessionMap.put(clientId, session);
    }


    /**
     * 删除session
     */
    public static void removeLocalSession(String clientId) {
        if (!localSessionMap.containsKey(clientId)) {
            return;
        }
        localSessionMap.remove(clientId);
    }


    public static LocalSession get(String clientId){
        return localSessionMap.get(clientId);
    }
    /**
     * 根据用户id，获取session对象
     */
    public static LocalSession getSessionsBy(String clientId) {
        return localSessionMap.get(clientId);

    }


    //关闭连接
    public static void closeSession(ChannelHandlerContext ctx) {

        LocalSession session =
                ctx.channel().attr(LocalSession.SESSION_KEY).get();

        if (null != session && session.isValid()) {
            session.close();
            removeLocalSession(session.getClientId());
        }
    }


}
